<template>
  <div class="app-container">
    <!-- 搜索筛选区域 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="题目名称" prop="problemName">
          <el-input
            v-model="queryParams.problemName"
            placeholder="请输入题目名称"
            clearable
            size="small"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="题目难度" prop="difficulty">
          <el-select
            v-model="queryParams.difficulty"
            placeholder="请选择难度"
            clearable
            size="small"
            style="width: 150px"
          >
            <el-option label="简单" value="简单" />
            <el-option label="中等" value="中等" />
            <el-option label="困难" value="困难" />
          </el-select>
        </el-form-item>
        <el-form-item label="题目分类" prop="category">
          <el-select
            v-model="queryParams.category"
            placeholder="请选择分类"
            clearable
            size="small"
            style="width: 150px"
          >
            <el-option label="基础算法" value="基础算法" />
            <el-option label="数据结构" value="数据结构" />
            <el-option label="动态规划" value="动态规划" />
            <el-option label="图论" value="图论" />
            <el-option label="数学" value="数学" />
          </el-select>
        </el-form-item>
        <el-form-item label="题目状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            size="small"
            style="width: 150px"
          >
            <el-option label="启用" value="启用" />
            <el-option label="禁用" value="禁用" />
            <el-option label="维护" value="维护" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="action-card">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:oj:problems:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:oj:problems:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:oj:problems:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:oj:problems:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="problemList"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="题目ID" align="center" prop="problemId" width="120" />
        <el-table-column label="题目名称" align="center" prop="problemName" width="200" />
        <el-table-column label="难度" align="center" prop="difficulty" width="80">
          <template slot-scope="scope">
            <el-tag :type="getDifficultyTagType(scope.row.difficulty)">
              {{ scope.row.difficulty }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="分值" align="center" prop="score" width="80" />
        <el-table-column label="时间限制" align="center" prop="timeLimit" width="100">
          <template slot-scope="scope">
            {{ scope.row.timeLimit }}ms
          </template>
        </el-table-column>
        <el-table-column label="内存限制" align="center" prop="memoryLimit" width="100">
          <template slot-scope="scope">
            {{ scope.row.memoryLimit }}MB
          </template>
        </el-table-column>
        <el-table-column label="分类" align="center" prop="category" width="120" />
        <el-table-column label="提交次数" align="center" prop="submissionCount" width="100" />
        <el-table-column label="通过次数" align="center" prop="acceptedCount" width="100" />
        <el-table-column label="通过率" align="center" prop="acceptanceRate" width="100">
          <template slot-scope="scope">
            <el-progress 
              :percentage="scope.row.acceptanceRate" 
              :color="getAcceptanceRateColor(scope.row.acceptanceRate)"
              :stroke-width="8"
            />
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" width="80">
          <template slot-scope="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row)"
              v-hasPermi="['system:oj:problems:query']"
            >查看</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:oj:problems:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:oj:problems:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 新增/修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="题目ID" prop="problemId">
              <el-input v-model="form.problemId" placeholder="请输入题目ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="题目名称" prop="problemName">
              <el-input v-model="form.problemName" placeholder="请输入题目名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="难度" prop="difficulty">
              <el-select v-model="form.difficulty" placeholder="请选择难度" style="width: 100%">
                <el-option label="简单" value="简单" />
                <el-option label="中等" value="中等" />
                <el-option label="困难" value="困难" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分值" prop="score">
              <el-input-number v-model="form.score" :min="0" :max="100" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分类" prop="category">
              <el-select v-model="form.category" placeholder="请选择分类" style="width: 100%">
                <el-option label="基础算法" value="基础算法" />
                <el-option label="数据结构" value="数据结构" />
                <el-option label="动态规划" value="动态规划" />
                <el-option label="图论" value="图论" />
                <el-option label="数学" value="数学" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="时间限制" prop="timeLimit">
              <el-input-number v-model="form.timeLimit" :min="100" :max="10000" style="width: 100%" />
              <span style="margin-left: 10px; color: #666;">ms</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="内存限制" prop="memoryLimit">
              <el-input-number v-model="form.memoryLimit" :min="16" :max="1024" style="width: 100%" />
              <span style="margin-left: 10px; color: #666;">MB</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="题目描述" prop="problemDescription">
          <el-input
            v-model="form.problemDescription"
            type="textarea"
            :rows="6"
            placeholder="请输入题目描述"
            show-word-limit
            maxlength="5000"
          />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="输入格式" prop="inputFormat">
              <el-input
                v-model="form.inputFormat"
                type="textarea"
                :rows="4"
                placeholder="请输入输入格式说明"
                show-word-limit
                maxlength="1000"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="输出格式" prop="outputFormat">
              <el-input
                v-model="form.outputFormat"
                type="textarea"
                :rows="4"
                placeholder="请输入输出格式说明"
                show-word-limit
                maxlength="1000"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="题目标签" prop="tags">
          <el-input v-model="form.tags" placeholder="请输入题目标签，多个标签用逗号分隔" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="启用" value="启用" />
                <el-option label="禁用" value="禁用" />
                <el-option label="维护" value="维护" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog title="题目详情" :visible.sync="viewOpen" width="900px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="题目ID">{{ viewForm.problemId }}</el-descriptions-item>
        <el-descriptions-item label="题目名称">{{ viewForm.problemName }}</el-descriptions-item>
        <el-descriptions-item label="难度">{{ viewForm.difficulty }}</el-descriptions-item>
        <el-descriptions-item label="分值">{{ viewForm.score }}</el-descriptions-item>
        <el-descriptions-item label="时间限制">{{ viewForm.timeLimit }}ms</el-descriptions-item>
        <el-descriptions-item label="内存限制">{{ viewForm.memoryLimit }}MB</el-descriptions-item>
        <el-descriptions-item label="分类">{{ viewForm.category }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ viewForm.status }}</el-descriptions-item>
        <el-descriptions-item label="提交次数">{{ viewForm.submissionCount }}</el-descriptions-item>
        <el-descriptions-item label="通过次数">{{ viewForm.acceptedCount }}</el-descriptions-item>
        <el-descriptions-item label="通过率">{{ viewForm.acceptanceRate }}%</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(viewForm.createdAt) }}</el-descriptions-item>
      </el-descriptions>
      
      <el-divider content-position="left">题目描述</el-divider>
      <div class="problem-description">{{ viewForm.problemDescription }}</div>
      
      <el-divider content-position="left">输入格式</el-divider>
      <div class="problem-format">{{ viewForm.inputFormat }}</div>
      
      <el-divider content-position="left">输出格式</el-divider>
      <div class="problem-format">{{ viewForm.outputFormat }}</div>
      
      <el-divider content-position="left">题目标签</el-divider>
      <div class="problem-tags">
        <el-tag 
          v-for="tag in viewForm.tags ? viewForm.tags.split(',') : []" 
          :key="tag" 
          style="margin-right: 10px; margin-bottom: 10px;"
        >
          {{ tag }}
        </el-tag>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProblem, getProblem, delProblem, addProblem, updateProblem } from "@/api/system/oj-practice";

export default {
  name: "OjProblems",
  components: {
    Pagination: () => import("@/components/Pagination")
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 题目列表数据
      problemList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示查看弹出层
      viewOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        problemName: null,
        difficulty: null,
        category: null,
        status: null
      },
      // 表单参数
      form: {},
      // 查看表单参数
      viewForm: {},
      // 表单校验
      rules: {
        problemId: [
          { required: true, message: "题目ID不能为空", trigger: "blur" }
        ],
        problemName: [
          { required: true, message: "题目名称不能为空", trigger: "blur" }
        ],
        difficulty: [
          { required: true, message: "难度不能为空", trigger: "change" }
        ],
        score: [
          { required: true, message: "分值不能为空", trigger: "blur" }
        ],
        category: [
          { required: true, message: "分类不能为空", trigger: "change" }
        ],
        problemDescription: [
          { required: true, message: "题目描述不能为空", trigger: "blur" }
        ],
        inputFormat: [
          { required: true, message: "输入格式不能为空", trigger: "blur" }
        ],
        outputFormat: [
          { required: true, message: "输出格式不能为空", trigger: "blur" }
        ],
        timeLimit: [
          { required: true, message: "时间限制不能为空", trigger: "blur" }
        ],
        memoryLimit: [
          { required: true, message: "内存限制不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询题目列表 */
    getList() {
      this.loading = true;
      listProblem(this.queryParams).then(response => {
        this.problemList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        problemId: null,
        problemName: null,
        problemDescription: null,
        inputFormat: null,
        outputFormat: null,
        difficulty: null,
        score: 10,
        timeLimit: 1000,
        memoryLimit: 128,
        category: null,
        tags: null,
        status: "启用",
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.problemId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加题目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const problemId = row.problemId || this.ids[0];
      getProblem(problemId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改题目";
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.viewForm = { ...row };
      this.viewOpen = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.problemId != null) {
            updateProblem(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProblem(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const problemIds = row.problemId || this.ids;
      this.$modal.confirm('是否确认删除题目编号为"' + problemIds + '"的数据项？').then(function() {
        return delProblem(problemIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/oj/problem/export', {
        ...this.queryParams
      }, `oj_problem_${new Date().getTime()}.xlsx`);
    },
    // 表单重置工具方法
    resetForm(refName) {
      if (this.$refs[refName]) {
        this.$refs[refName].resetFields();
      }
    },
    // 时间格式化工具方法
    parseTime(time, cFormat) {
      if (arguments.length === 0 || !time) {
        return null;
      }
      const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
      let date;
      if (typeof time === 'object') {
        date = time;
      } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
          time = parseInt(time);
        } else if (typeof time === 'string') {
          time = time.replace(new RegExp(/-/gm), '/');
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
          time = time * 1000;
        }
        date = new Date(time);
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      };
      const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key];
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value]; }
        return value.toString().padStart(2, '0');
      });
      return time_str;
    },
    // 获取难度标签类型
    getDifficultyTagType(difficulty) {
      const typeMap = {
        '简单': 'success',
        '中等': 'warning',
        '困难': 'danger'
      };
      return typeMap[difficulty] || 'info';
    },
    // 获取状态标签类型
    getStatusTagType(status) {
      const typeMap = {
        '启用': 'success',
        '禁用': 'danger',
        '维护': 'warning'
      };
      return typeMap[status] || 'info';
    },
    // 获取通过率颜色
    getAcceptanceRateColor(rate) {
      if (rate >= 80) return '#67C23A';
      if (rate >= 60) return '#E6A23C';
      if (rate >= 40) return '#F56C6C';
      return '#909399';
    }
  }
};
</script>

<style scoped>
.search-card {
  margin-bottom: 20px;
}

.action-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

.problem-description,
.problem-format {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  line-height: 1.6;
  white-space: pre-wrap;
}

.problem-tags {
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.el-divider {
  margin: 20px 0;
}
</style> 